package org.gd136.ce.script;

import org.gd136.ce.game.GS;

public abstract class Script {
	protected String fileName;
	protected int lineNum;
	protected Script nextScript;

	protected static Script tmp;

	public class SM extends ScriptManager {
	}

	protected void continueExecuteNext() {
		SM.nextScript();
		SM.getCurrentScript().execute(GS.scriptStage);
	}

	public class Argument {
		public int endIndex;
		public String argumentName;
		public String[] arguments;
	}

	protected Argument readNextArguments(String src, int startIndex) {
		while (src.length() > startIndex && src.charAt(startIndex) == ' ') {
			startIndex++;
		}
		if (src.length() <= startIndex) {
			return null;
		}
		Argument arg = new Argument();
		int pa = src.indexOf('(', startIndex);
		int pn = src.indexOf(' ', startIndex);
		if (pn < 0) {//no next argument
			arg.endIndex = src.length();
		} else {
			if (pa > pn) {
				pa = -1;
			}
			arg.endIndex = pn;
		}

		if (pa < 0) {
			arg.argumentName = src.substring(startIndex, arg.endIndex);
		} else {
			arg.argumentName = src.substring(startIndex, pa);
			int pb = src.indexOf(')', pa);
			arg.endIndex = pb + 1;
			String args = src.substring(pa + 1, pb);
			arg.arguments = args.split(",");
		}
		//		System.out.println("ARG:" + arg.argumentName + " :"
		//				+ Arrays.toString(arg.arguments));
		return arg;
	}

	protected void addToPoolAndLinkFrontScript() {
		if (tmp != null) {
			tmp.nextScript = this;
		}
		addToPool();
	}

	protected void addToPool() {
		SM.currentPart.add(this);
		tmp = this;
	}

	public void setScriptSrc(String fileName, int lineNum) {
		this.fileName = fileName;
		this.lineNum = lineNum;
	}

	public abstract Script readScript(String scriptLine);

	public abstract void execute(ScriptStage stage);

	public void stageCallBack(Object result) {
	}

	public Script nextScript() {
		return nextScript;
	}
}
